/**
 * 医疗管理系统API工具
 * 用于处理前端API请求
 */

// API基础URL
const API_BASE_URL = window.location.origin;

// 默认请求头
const DEFAULT_HEADERS = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
};

/**
 * 获取JWT token
 * @returns {string} JWT token
 */
function getToken() {
    return localStorage.getItem('token');
}

/**
 * 添加授权头
 * @returns {Object} 包含授权的请求头
 */
function getAuthHeaders() {
    const headers = { ...DEFAULT_HEADERS };
    const token = getToken();
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }
    return headers;
}

/**
 * 处理API响应
 * @param {Response} response - fetch API的响应对象
 * @returns {Promise} 处理后的响应数据
 */
async function handleResponse(response) {
    const data = await response.json();
    
    if (!response.ok) {
        const error = (data && data.message) || response.statusText;
        return Promise.reject(error);
    }
    
    return data;
}

/**
 * 发送GET请求
 * @param {string} url - 请求URL
 * @returns {Promise} 响应数据
 */
async function get(url) {
    const requestOptions = {
        method: 'GET',
        headers: getAuthHeaders()
    };
    
    const response = await fetch(`${API_BASE_URL}${url}`, requestOptions);
    return handleResponse(response);
}

/**
 * 发送POST请求
 * @param {string} url - 请求URL
 * @param {Object} body - 请求体
 * @returns {Promise} 响应数据
 */
async function post(url, body) {
    const requestOptions = {
        method: 'POST',
        headers: getAuthHeaders(),
        body: JSON.stringify(body)
    };
    
    const response = await fetch(`${API_BASE_URL}${url}`, requestOptions);
    return handleResponse(response);
}

/**
 * 发送PUT请求
 * @param {string} url - 请求URL
 * @param {Object} body - 请求体
 * @returns {Promise} 响应数据
 */
async function put(url, body) {
    const requestOptions = {
        method: 'PUT',
        headers: getAuthHeaders(),
        body: JSON.stringify(body)
    };
    
    const response = await fetch(`${API_BASE_URL}${url}`, requestOptions);
    return handleResponse(response);
}

/**
 * 发送DELETE请求
 * @param {string} url - 请求URL
 * @returns {Promise} 响应数据
 */
async function del(url) {
    const requestOptions = {
        method: 'DELETE',
        headers: getAuthHeaders()
    };
    
    const response = await fetch(`${API_BASE_URL}${url}`, requestOptions);
    return handleResponse(response);
}

/**
 * 登录请求
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @returns {Promise} 登录响应
 */
async function login(username, password) {
    return post('/api/auth/login', { username, password });
}

/**
 * 注销请求
 * @returns {Promise} 注销响应
 */
async function logout() {
    // 清除本地存储的token
    localStorage.removeItem('token');
    return post('/api/auth/logout', {});
}

/**
 * 获取当前用户信息
 * @returns {Promise} 用户信息
 */
async function getCurrentUser() {
    return get('/api/users/current');
}

/**
 * 发送AI诊断消息
 * @param {string} message - 消息内容
 * @param {string} sessionId - 会话ID
 * @param {number} userId - 用户ID
 * @returns {Promise} AI响应
 */
async function sendAiDiagnosisMessage(message, sessionId, userId) {
    return post('/api/ai-diagnosis/chat', { 
        message, 
        sessionId, 
        userId: userId || getCurrentUserId()
    });
}

/**
 * 获取当前用户ID
 * @returns {number} 用户ID
 */
function getCurrentUserId() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    return userInfo.userId;
}

/**
 * 获取聊天历史
 * @param {number} userId - 用户ID
 * @param {string} sessionId - 会话ID
 * @returns {Promise} 聊天历史
 */
async function getChatHistory(userId, sessionId) {
    return get(`/api/chat-history/${userId}/${sessionId}`);
}

/**
 * 导出诊断报告
 * @param {number} patientId - 患者ID
 * @returns {Promise} 报告URL
 */
async function exportDiagnosisReport(patientId) {
    return get(`/api/ai-diagnosis/export-report/${patientId}`);
}

// 导出API函数
window.api = {
    get,
    post,
    put,
    delete: del,
    login,
    logout,
    getCurrentUser,
    sendAiDiagnosisMessage,
    getChatHistory,
    exportDiagnosisReport
}; 